package org.flint92.springcloud.previous.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author flint92
 */
public class SpringEventDemo {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        // add listener
//        context.addApplicationListener(new CustomApplicationListener());
        // register listener
        context.register(CustomApplicationListener.class);

        // start up
        context.refresh();

        // publish event
        context.publishEvent(new CustomApplicationEvent("Hello Event!"));
        context.publishEvent(new CustomApplicationEvent("123"));

    }

    private static class CustomApplicationEvent extends ApplicationEvent {

        private static final long serialVersionUID = 3063759987445363481L;

        /**
         * Create a new ApplicationEvent.
         *
         * @param source the object on which the event initially occurred (never {@code null})
         */
        public CustomApplicationEvent(Object source) {
            super(source);
        }
    }

    @Component
    private static class CustomApplicationListener implements ApplicationListener<CustomApplicationEvent> {

        @Override
        public void onApplicationEvent(CustomApplicationEvent event) {
            System.out.printf("CustomApplicationListener receives event source: %s\n", event.getSource());
        }
    }

}
